<?php
/*******************************************************************************
 * $Date:: Sep 29, 2011 10:45:36 AM                                            $
 * $Revision:                                                                  $
 * $Author:: Tuan Duong                                                        $
 * $Comment::                                                                  $
 ******************************************************************************/ 
/**
 * User controller for front-end
 * 
 * @package Lua
 * @subpackage Controller
 * @author Tuan Duong <bacduong[at]gmail[dot]com>
 * @version 
 */

class UserController extends Lua_Controller_Default
{
	private $locationService;
	private $userService;
    private $friendService;
    	
	public function __construct() {
		parent::__construct();
		$this->locationService = Lua_Service_Locator::getInstance()->getService("Location");
		$this->userService = Lua_Service_Locator::getInstance()->getService("User");
		$this->friendService = Lua_Service_Locator::getInstance()->getService("Friend");
		
	}
    /**
     * Index Action
     */
    public function indexAction()
    {
        
    }
    
    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->redirect(array(
            Lua_Constant_General::PARAM_CONTROLLER => "index",
            Lua_Constant_General::PARAM_ACTION => "index"
        ));
    }
    
    public function registerAction() {
    	$countryId="VN";
    	$cities = $this->locationService->findCitiesByCountryId($countryId);
    	$countries = $this->locationService->findAllCountries();
    	$this->view->assign('countries', $countries);
    	$this->view->assign('cities', $cities);
    }
    
    public function registerSubmitAction() {
    	$ipooUser = new Lua_Bean_IpooUser($_REQUEST);
    	$errors = $this->userService->validateAddUser($ipooUser);
    	if ($_POST["recaptcha_response_field"]) {
    			$recaptchaConfig = Lua_Config::load(array('recaptcha'));
				$recaptchaKey = $recaptchaConfig['key'];
        		$resp = recaptcha_check_answer ($recaptchaKey['private'],
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);
			if (!$resp->is_valid) {
		         $errors['captcha'] = Lua_Constant_Error::INCORRECT_ERROR;                           	
			}
    	} else {
    		$errors['captcha'] = Lua_Constant_Error::MISSING_ERROR;
    	}
    	if (sizeof($errors) > 0) {
    		$this->view->assign('errors', $errors);
    		$this->forward(array(Lua_Constant_General::PARAM_ACTION => 'register'));
    	} else {
    		$this->userService->addUser($ipooUser, array(Lua_Constant_Group::USER_GROUP_ID));
	        $username = Lua_Request::getInstance()->getPost('username', '');
	        $password = Lua_Request::getInstance()->getPost('password', '');
	        $auth = new Lua_Auth_User($username, $password);
	        $result = Zend_Auth::getInstance()->authenticate($auth);
	        $this->redirect(array(
	    		Lua_Constant_General::PARAM_CONTROLLER => "user",
	            Lua_Constant_General::PARAM_ACTION => "profile"
            ));
	        
    	}
    	
    }
    /**
     * 
     * Handle update avatar photo action in [application\default\views\scripts\user\profile.phtml] page
     * 
     */
    public function updateAvatarAction() {
    	$avatarFile = $_FILES["avatar"];
    	$errors = $this->userService->validateUpdateAvatar($avatarFile);
    	if (sizeof($errors) == 0) {
			$this->userService->updateAvatar();
    	} else {
    		$this->view->assign('errors', $errors);
			
		}
		$this->forward(array(Lua_Constant_General::PARAM_ACTION => 'profile'));
    }

    /**
     * 
     * Handle update contact action in [application\default\views\scripts\user\profile.phtml] page
     * 
     */
    public function updateContactAction() {
    	
    	$ipooUser = new Lua_Bean_IpooUser($_REQUEST);
    	$errors = $this->userService->validateUpdateContactRequest($ipooUser);
    	if (sizeof($errors) == 0) {
    		$this->userService->updateContact($ipooUser);
    		$this->view->assign('message', 'Cập nhật thông tin liên hệ thành công.');
    	}
    	$this->forward(array(
	    		Lua_Constant_General::PARAM_CONTROLLER => "user",
	            Lua_Constant_General::PARAM_ACTION => "profile"
            ));
    }
    
    public function changePassAction() {
    	$oldPassword = trim($_REQUEST['password']);
    	$newPassword = trim($_REQUEST['new_password']);
    	$errors = $this->userService->validateChangePass($oldPassword, $newPassword);
    	if (sizeof($errors) == 0) {
    		$this->userService->changePass($newPassword);
    		
    		$this->view->assign('message', 'Mật khẩu thay đổi thành công.');
    	}
    	$this->view->assign('errors', $errors);
    	
		$this->forward(array(Lua_Constant_General::PARAM_ACTION => 'profile'));
    }
    
    public function profileAction() {
    	$auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
    		$identity = $auth->getIdentity();
            $userId = $identity->id;
    		$loginUser = $this->userService->findUserByProperty("id", $userId);
            $loginUser = $loginUser[0];
            $loginUser['econtact'] = $this->userService->parseEcontactToArray($loginUser['econtact']);
            $friends = $this->friendService->findFriendsOfUser($userId);
            $this->view->assign('friends', $friends);
            $this->view->assign('loginUser', $loginUser);
        }
    }
    
	public function deleteFriendAction() {
    	$auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
    		$identity = $auth->getIdentity();
            $userId = $identity->id;
            $friendId = $_REQUEST['fId'];
            $this->friendService->deleteFriendOfUser($userId, $friendId);
            $this->forward(array(Lua_Constant_General::PARAM_ACTION => 'profile'));
        }
    }
}